package org.redrock.test.repository;

import okhttp3.*;
import org.redrock.test.bean.RequestInfo;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;

@Repository
public class NetworkRepository {

    private final String MEDIA_TYPE = "application/x-www-form-urlencoded;charset=utf-8";

    public String curl(RequestInfo requestInfo) {
        String result = null;
        try {
            String url = requestInfo.getUrl();
            String raw = null;
            if (!CollectionUtils.isEmpty(requestInfo.getParams())) {
                Map<String, String> params = requestInfo.getParams();
                StringBuilder builder = new StringBuilder();
                for (Map.Entry<String, String> param : params.entrySet())
                    builder.append(param.getKey()).append("=").append(param.getValue()).append("&");
                builder.substring(0, builder.lastIndexOf("&"));
                raw = builder.toString();
            }
            if (!StringUtils.isEmpty(requestInfo.getRaw())) raw = requestInfo.getRaw();
            Request.Builder requestBuilder = new Request.Builder();
            if (requestInfo.getMethod().equalsIgnoreCase("get")) {
                url += (url.indexOf("?") < 0 ? "?" : "&") + raw;
                requestBuilder.url(url).get();
            } else {
                MediaType mediaType = MediaType.parse(
                        StringUtils.isEmpty(requestInfo.getMediaType()) ? MEDIA_TYPE : requestInfo.getMediaType()
                );
                RequestBody requestBody = RequestBody.create(mediaType, raw);
                requestBuilder.post(requestBody);
            }
            if (!CollectionUtils.isEmpty(requestInfo.getHeaders())) {
                Map<String, String> headers = requestInfo.getHeaders();
                for (Map.Entry<String, String> header : headers.entrySet())
                    requestBuilder.addHeader(header.getKey(), header.getValue());
            }
            Request request = requestBuilder.build();
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {

        }
        return result;
    }
}
